package org.myorg;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;

public class FPeople implements Serializable {
	public int p_num;
	public FGene persons[];

	public FPeople() {
		p_num = 0;
	}
	
	public FPeople(int num,int length) {
		p_num = num;
		persons = new FGene[num];

		double[] low = new double[length];
		double[] high = new double[length];
 		for(int i = 0; i < num; i++) {
			persons[i] = new FGene(length,low, high);
		}
	}
	
	public FPeople(int num) {
		p_num = num;
		persons = new FGene[num];
	}
	
	public FPeople(FPeople people) {
		this.p_num = people.p_num;
		this.persons = new FGene[people.p_num];
		for ( int i = 0; i < people.p_num; i++){
			this.persons[i] = new FGene(people.persons[i]);
		}

	}

	public FPeople(int num, int length, double low[], double high[]) {
		p_num = num;
		persons = new FGene[num];

		for(int i = 0; i < num; i++) {
			persons[i] = new FGene(length,low, high);
		}
		//System.out.println(persons[0]);
	}
	
	public void add(FPeople p) {
				
		ArrayList<FGene> all_p =  new ArrayList<FGene>(0);
		
		for (int i = 0; i < this.p_num; i++) {
			all_p.add(this.persons[i]);
		}
		
		for (int i = 0; i < p.p_num; i++) {
			all_p.add(p.getPersons()[i]);
		}
		
		this.p_num = this.p_num + p.p_num;

		this.persons = all_p.toArray(new FGene[all_p.size()]);
	}
	
	public FPeople[] seg(int num) {
		FPeople[] ap = new FPeople[num];
		int size = p_num/num;
		for (int i = 0; i < num ; i++) {
			ap[i] = new FPeople(size);
			for (int j = 0; j < size; j++) {
				ap[i].persons[j] = new FGene(persons[i*size + j]);
			}
		}
		return ap;
	}
	
	public void caculateFitness(Fc function) {
		for (int i = 0; i < p_num; i++) {
			function.caculate(persons[i]);
		}
	}

	public int getBest(Fc function) {
		int res = 0;
		for (int i = 0; i<p_num; i++) {
			if(function.better(persons[i],persons[res]))
				res = i;
		}
		return res;
	}


	public FGene[] getPersons() {
		return persons;
	}

}
